package com.zwkj.util;

import cn.hutool.core.io.file.FileNameUtil;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.Map;

/**
 * @author xurui
 */
@Log
@Component
public class MinioFileUploadUtil {
    @Value("${minio.url}")
    private String url;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.web-url}")
    private String webUrl;

    /**
     * 通过网络路径 从minio下载文件
     *
     * @throws IOException
     */
    public byte[] minioUrlDownload(String fileUrl) {
        byte[] result = null;
        try {
            MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
            String extName = FileNameUtil.extName(fileUrl);
            String mainName = FileNameUtil.mainName(fileUrl);
            String split = fileUrl.replace(webUrl, "");
            String[] tempS = split.split("/");
            String bucketName = tempS[0];
            String fileBacketUrl = "";
            for (int i = 1; i < tempS.length; i++) {
                fileBacketUrl = fileBacketUrl + (fileBacketUrl == "" ? tempS[i] : "/" + tempS[i]);
            }
            InputStream inputStream = minioClient.getObject(bucketName, fileBacketUrl);
            //创建模板文件
            File mobanTempFile = File.createTempFile(mainName, "." + extName);
            org.apache.commons.io.FileUtils.copyInputStreamToFile(inputStream, mobanTempFile);
            inputStream.close();
            result = com.zwkj.util.FileUtils.readAllBytes(Paths.get(mobanTempFile.getPath()));
            mobanTempFile.delete();
//            FileUtils.forceDelete(mobanTempFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public void minioUrlUpload(MultipartFile file, String fileUrl) {
        String split = fileUrl.replace(webUrl, "");
        String[] tempS = split.split("/");
        String bucketName = tempS[0];
        String fileBacketUrl = "";
        for (int i = 1; i < tempS.length; i++) {
            fileBacketUrl = fileBacketUrl + (fileBacketUrl == "" ? tempS[i] : "/" + tempS[i]);
        }
        try {
            MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
            minioClient.putObject(bucketName, fileBacketUrl, file.getInputStream(), file.getContentType());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}